﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

/// <summary>
/// SerializeUtil 的摘要描述
/// </summary>
/// 

namespace com.pro2e.console.core.util
{
    public class SerializeUtil
    {
        public SerializeUtil()
        {

        }


        /// <summary>
        /// 序列化物件成string
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string Serialize(object o)
        {
            byte[] bytes;
            long length = 0;
            MemoryStream ws = new MemoryStream();
            BinaryFormatter sf = new BinaryFormatter();
            sf.Serialize(ws, o);
            length = ws.Length;
            bytes = ws.GetBuffer();
            string encodedData = Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None);
            return encodedData;
        }

        /// <summary>
        /// 反序列化為物件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="o"></param>
        /// <returns></returns>
        public static T DeSerialize<T>(string str)
        {

            MemoryStream ws = new MemoryStream(Convert.FromBase64String(str));
            BinaryFormatter sf = new BinaryFormatter();
            object obj = sf.Deserialize(ws);
            return (T)obj;

        }
    }
}